//
//  CodingModel.m
//  IPTest
//
//  Created by sank zhang on 2019/1/7.
//  Copyright © 2019年 sank zhang. All rights reserved.
//

#import "CodingModel.h"
#import <objc/runtime.h>
#import <objc/message.h>

@implementation CodingModel

- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    if (self = [super init]) {
        unsigned int count = 0;
        Ivar *ivarList = class_copyIvarList([self class], &count);
        for (int i = 0; i < count; i++) {
            Ivar ivar = ivarList[i];
            const char *ivarName = ivar_getName(ivar);
            NSString *key = [NSString stringWithUTF8String:ivarName];
            id value = [aDecoder decodeObjectForKey:key];
            [self setValue:value forKey:key];
        }
        free(ivarList);
    }
    return self;
}

- (void)encodeWithCoder:(NSCoder *)aCoder
{
    unsigned int count = 0;
    Ivar *ivarList = class_copyIvarList([self class], &count);
    for (int i = 0; i < count; i++) {
        Ivar ivar = ivarList[i];
        const char *ivarName = ivar_getName(ivar);
        NSString *key = [NSString stringWithUTF8String:ivarName];
        id value = [self valueForKey:key];
        
        [aCoder encodeObject:value forKey:key];
    }
    free(ivarList);
}
@end
